package com.example.capsule_chat0322.request;

import android.content.Context;
import android.os.Build;
import android.os.Handler;

import androidx.annotation.RequiresApi;

import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.configuration.HttpConstant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.utils.AlterUtils;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author zhuzhiming
 * @Date 2022/5/5 20:55
 */
public class UserInfoRequest {

    public static void doGetUserInfoRequest(Handler handler, String userId) {

        if (userId == null) {
            return;
        }

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/getUserInfo/" + userId)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AlterUtils.alertByToastInSonThread((Context) GlobalAssistMap.getObject("context"), "查询个人信息失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String user = response.body().string();
                UserInfoBean userInfoBean = new Gson().fromJson(user, UserInfoBean.class);

                if (userInfoBean == null) {
                    return;
                }
                GlobalAssistMap.putObject(userInfoBean.getId() + "Info", userInfoBean);
                handler.sendMessage(handler.obtainMessage(1, userInfoBean));

            }
        });


    }


    public static UserInfoBean doGetUserInfoRequestSync(String userId) {

        if (userId == null) {
            return null;
        }

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/getUserInfo/" + userId)
                .build();

        Call call = httpClient.newCall(request);
        try {
            Response response = call.execute();
            String resBody = response.body().string();
            UserInfoBean userInfoBean = new Gson().fromJson(resBody, UserInfoBean.class);
            return userInfoBean;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void doUpdateUserInfoRequest(Handler handler, UserInfoBean userInfoBean) {

        if (userInfoBean == null) {
            return;
        }

        Gson gson = new Gson();
        //使用Gson将对象转换为json字符串
        String json = gson.toJson(userInfoBean);

        //MediaType 设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/updateUserInfo")
                .post(requestBody)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AlterUtils.alertByToastInSonThread((Context) GlobalAssistMap.getObject("context"), "更新信息失败！");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String res = response.body().string();
                if (res.equals(Constant.SUCCESS)) {
                    handler.sendMessage(handler.obtainMessage(1, res));
                    return;
                }
                handler.sendMessage(handler.obtainMessage(1, res));
                AlterUtils.alertByToastInSonThread((Context) GlobalAssistMap.getObject("context"), "更新信息失败！");
            }
        });


    }


    public static void uploadAvatar(Handler handler, String messageBean) {
        //MediaType 设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , messageBean);

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/uploadAvatar")
                .post(requestBody)
                .build();
        Call call = httpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String avatarServerPath = response.body().string();
                handler.sendMessage(handler.obtainMessage(1, avatarServerPath));
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getAvatar(Handler handler, String senderAvatarPath) {


        final MessageBean[] messageBean = {new MessageBean()};
        messageBean[0].setFilePath(senderAvatarPath);

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean[0]));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getAvatar")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resBody = response.body().string();
                messageBean[0] = new Gson().fromJson(resBody, MessageBean.class);
                if (messageBean[0] == null) {
                    return;
                }

                if (!new File(Constant.IMAGE_PATH).exists()) {
                    new File(Constant.IMAGE_PATH).mkdirs();
                }
                String content = messageBean[0].getContent();
                try {
                    byte[] by = Base64.getDecoder().decode(content);
                    String path = Constant.IMAGE_PATH + senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/") + 1);
                    OutputStream out = new FileOutputStream(path);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
                    bufferedOutputStream.write(by);
                    out.flush();
                    out.close();
                    bufferedOutputStream.close();
                    handler.sendMessage(handler.obtainMessage(1, Constant.SUCCESS));

                } catch (Exception e) {

                }
            }
        });
    }


    public static void dealFriendApply( String messageBean) {
        //MediaType 设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , messageBean);

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/dealFriendApply")
                .post(requestBody)
                .build();
        Call call = httpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }
        });
    }


}
